/*! \file */
/// \addtogroup Wally
/// \{
#include "Arduino.h"				// include the standard Arduino library
#include <Wire.h>					// include the standard Wire (I2C/TWI/2-wire) library

#include "Wally.h"
#include "i2c_peripherals.h"


//Write to i2c SRAM


void writeRAM(uint16_t address, uint8_t data)
{

	Wire.beginTransmission(I2CaddrRAM);
	Wire.write((uint8_t)lowByte(address)); 
	Wire.write((uint8_t)highByte(address)); 
	Wire.write(data); 
	Wire.endTransmission(); 
}


byte readRAM(uint16_t address)
{

	Wire.beginTransmission(I2CaddrRAM);
	Wire.write((uint8_t)lowByte(address)); 
	Wire.write((uint8_t)highByte(address)); 
	Wire.endTransmission();
	Wire.requestFrom(I2CaddrRAM, 1); //only one byte

	if(Wire.available()) {
		return Wire.read();
	} else {
		Serial.print("Read error when addressing external RAM over I2C - address: ");
		Serial.println(address);
	}

}

void getRTCtime(uint8_t *timeDate)
{
	// Reset the register pointer
	Wire.beginTransmission(I2CaddrRTC);
	Wire.write((byte)0x00);
	Wire.endTransmission();
	Wire.requestFrom(I2CaddrRTC, 7);

	uint8_t second = bcd2dec(Wire.read());
	uint8_t minute = bcd2dec(Wire.read());
	uint8_t hour = bcd2dec(Wire.read() & 0b111111);	//24 hour time
	uint8_t weekDay = bcd2dec(Wire.read()); 		//0-6 -> sunday - Saturday
	uint8_t monthDay = bcd2dec(Wire.read());
	uint8_t month = bcd2dec(Wire.read());
	uint8_t year = bcd2dec(Wire.read());

	//print the date :  d/m/YY 23:59:59

	Serial.print(monthDay);
	Serial.print("/");
	Serial.print(month);
	Serial.print("/");
	Serial.print(year);
	Serial.print(" ");
	Serial.print(hour);
	Serial.print(":");
	Serial.print(minute);
	Serial.print(":");
	Serial.println(second);
	
	
	timeDate[0] = monthDay;
	timeDate[1] = month;
	timeDate[2] = hour;
	timeDate[3] = minute;

}

void setRTCtime(void)
{
  	byte second =	   00;	//0-59
  	byte minute =	   25;	//0-59
  	byte hour =		   18;	//0-23
  	byte weekDay =		1;	//1-7
  	byte monthDay =	    7;	//1-31
  	byte month =		5;	//1-12
  	byte year  =	   12;	//0-99

	Wire.beginTransmission(I2CaddrRTC);
	Wire.write((byte)0x00); //stop Oscillator

	Wire.write(dec2bcd(second));
	Wire.write(dec2bcd(minute));
	Wire.write(dec2bcd(hour));
	Wire.write(dec2bcd(weekDay));
	Wire.write(dec2bcd(monthDay));
	Wire.write(dec2bcd(month));
	Wire.write(dec2bcd(year));
	Wire.write((byte)0x00); //start Oscillator

  Wire.endTransmission();

}

uint8_t dec2bcd(uint8_t val)
{
	return ((val/10*16)+(val%10));
}


uint8_t bcd2dec(uint8_t val)
{
	return ((val/16*10)+(val%16));
}

/// \}
